<template>
  <el-select v-model="selectValue" clearable :placeholder="placeholder" @change="selectData">
    <el-option v-for="item in list" :label="item[labelName]" :key="item[valueName]" :value="item[valueName]"></el-option>

    <el-pagination
      v-if="isPager"
      :current-page="pager.page"
      :page-size="pager.size"
      :page-sizes="[10, 20, 50, 100]"
      :layout="pagination.layout || 'total, sizes, prev, pager, next, jumper'"
      :total="total"
      background
      v-bind="pagination"
      @size-change="(size: number) => refreshData({ size, page: 1 })"
      @current-change="(page: number) => refreshData({ page })"
      class="k-pagination"
    >
    </el-pagination>
  </el-select>
</template>

<script lang="ts" setup>
  import { computed, defineComponent, ref, watch, type PropType } from 'vue'
  const props = defineProps ({
    selectValue: {
      type: String,
      default: ''
    },
    dataList: {
      type: Array,
      default: () => []
    },
    labelName: {
      type: String,
      default: 'label'
    },
    valueName: {
      type: String,
      default: 'value'
    },
    isPager: {
      type: Boolean,
      default: true
    },
    pageNum: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: 10
    },
    pagination: {
      type: Object,
      default: () => {
        return {}
      }
    },
    total: {
      type: Number,
      default: 0
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    callback: Function,
    selectCallback: Function
  })

  const selectValue = ref()
  watch(() => props.selectValue,
    async () => {
      selectValue.value = props.selectValue
    }
  )
  // 默认值
  const list = computed(() =>
    props.dataList.map((v: any) => {
      return v
    })
  )

  // 分页逻辑
  const pager = ref({ page: props.pageNum, size: props.pageSize })
  // 刷新， 用户分页 / 暴露给父组件
  const refreshData = (newPager = {}) => {
    pager.value = { ...pager.value, ...newPager }
    selectValue.value = ''
    props.callback && props.callback(pager.value, selectValue.value, true)
  }
  const selectData = (newPager = {}) => {
    pager.value = { ...pager.value, ...newPager }
    let obj;
    if (selectValue.value === '') {
      obj = null
    } else {
      obj = props.dataList.find((item: any) => item.id === selectValue.value)
    }
    props.selectCallback && props.selectCallback(obj)
  }
</script>
